package com.weacar.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weacar.R;
import com.weacar.adapter.MessageCenterAdapter;
import com.weacar.bean.BaseBean;
import com.weacar.bean.LoginBean;
import com.weacar.bean.MessageBean;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.ToastUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 消息中心
 */
public class MessageCenterActivity extends BaseActivity {
    @BindView(R.id.lv_message)
    ListView lv_message;
    @BindView(R.id.rl_main)
    RelativeLayout rl_main;
    @BindView(R.id.refresh)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.iv_empty)
    ImageView iv_empty;

    MessageCenterAdapter messageCenterAdapter;

    private int page = 1;
    private int refresh_flag = 0;

    ArrayList<MessageBean.MsgBean> al;

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarStyle("1");
        setContentView(R.layout.activity_message_center);
        AppManager.getInstance().addActivity(this);
        ButterKnife.bind(this);
        al = new ArrayList<>();
        getMessage(refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                al.clear();
                refresh_flag = 0;
                page = 1;
                getMessage(refreshlayout);
            }
        });


        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refresh_flag = 1;
                page = page + 1;
                getMessage(refreshlayout);
            }
        });


    }

    // 获取消息列表数据
    public void getMessage(final RefreshLayout refreshlayout) {
        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }
        showLoading("数据加载中...");
        try {
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_message);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("page", page);
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    if (refresh_flag == 0) {
                        refreshlayout.finishRefresh();
                    } else if (refresh_flag == 1) {
                        refreshlayout.finishLoadmore();
                    }


                    LogUtils.d("result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        try {
                            MessageBean messageBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), MessageBean.class);
                            if (messageBean != null && messageBean.getMsg() != null) {
                                al.addAll(messageBean.getMsg());
                                if (al.size() != 0) {
                                    iv_empty.setVisibility(View.GONE);
                                } else {
                                    iv_empty.setVisibility(View.VISIBLE);
                                }

                                messageCenterAdapter = new MessageCenterAdapter(getApplicationContext(), R.layout.item_lv_message_center, al);
                                lv_message.setAdapter(messageCenterAdapter);
                                lv_message.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                        initNotice(al.get(i).getContent());
                                    }
                                });
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        // 错误信息提示
                        if (baseBean != null) {
                            try {
                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                ToastUtil.showShort(getApplicationContext(), jsonObject.get("msg").toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShort(getApplicationContext(), "系统异常");
                        }
                    }


                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 通知初始化
    public void initNotice(String content) {

        Resources resources = getApplication().getResources();

        DisplayMetrics displayMetrics = resources.getDisplayMetrics();

        int widthPixels = (int) (displayMetrics.widthPixels * 0.8);//当前屏幕宽

        int heightPixels = (int) (displayMetrics.heightPixels * 0.65);//当前屏幕高


        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_notice, null);
        TextView tv_close = contentView.findViewById(R.id.tv_close);
        TextView tv_content = contentView.findViewById(R.id.tv_content);
        tv_content.setText("        " + content);

        final CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(widthPixels, heightPixels)//显示大小
                .create()
                .showAtLocation(rl_main, Gravity.CENTER, 0, 0);

        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customPopWindow.dissmiss();
            }
        });
    }
}
